package com.zkjl.protect_business.service.impl;

import cn.hutool.core.util.IdUtil;
import com.zkjl.protect_business.common.BaseException;
import com.zkjl.protect_business.common.Status;
import com.zkjl.protect_business.dto.BusinessTrainingDTO;
import com.zkjl.protect_business.dto.PageDTO;
import com.zkjl.protect_business.entity.BusinessTraining;
import com.zkjl.protect_business.entity.Notice;
import com.zkjl.protect_business.repository.BusinessTrainingRepository;
import com.zkjl.protect_business.service.BusinessTrainingService;
import com.zkjl.protect_business.service.LogService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.*;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.zkjl.protect_business.common.Consts.OPERATION_ADD;
import static com.zkjl.protect_business.common.Consts.OPERATION_DEL;

@Service
public class BusinessTrainingServiceImpl implements BusinessTrainingService {

    @Autowired
    ModelMapper modelMapper;
    @Autowired
    BusinessTrainingRepository businessTrainingRepository;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    LogService logService;

    @Override
    public BusinessTraining save(BusinessTrainingDTO businessTrainingDTO) {
        BusinessTraining businessTraining = modelMapper.map(businessTrainingDTO, BusinessTraining.class);
        businessTraining.setId(IdUtil.simpleUUID());
        businessTraining.setBaseInfo();
        String name = businessTraining.getName();

        BusinessTraining save = businessTrainingRepository.save(businessTraining);
        logService.save("业务培训", name,OPERATION_ADD);

        return save;
    }

    @Override
    public PageImpl page(PageDTO pageDTO, String search, String type, Long startTime, Long endTime) {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        //全局关键词
        if (StringUtils.isNotEmpty(search)) {
            //精确匹配  https://blog.csdn.net/hereiskxm/article/details/47979013
            MultiMatchQueryBuilder type1 = new MultiMatchQueryBuilder(search).type(MultiMatchQueryBuilder.Type.PHRASE).slop(0);
            qb.filter(type1);
        }

        if (startTime != null && startTime != 0) {
            qb.filter(QueryBuilders.rangeQuery("create_time").gte(startTime));
        }
        if (endTime != null && endTime != 0) {
            qb.filter(QueryBuilders.rangeQuery("create_time").lt(endTime));
        }

        if (StringUtils.isNotEmpty(type)) {
            qb.filter(new QueryStringQueryBuilder(type).field("type").defaultOperator(Operator.AND));
        }
        queryBuilder.withQuery(qb);


        //分页
        Pageable pageable = PageRequest.of(pageDTO.getPageNum() - 1, pageDTO.getPageSize(), Sort.Direction.DESC, "create_time");
        queryBuilder.withPageable(pageable);

        SearchHits<BusinessTraining> search1 = elasticsearchRestTemplate.search(queryBuilder.build(), BusinessTraining.class);
        List<BusinessTraining> collect = search1.stream().map(SearchHit::getContent).collect(Collectors.toList());

        long total = search1.getTotalHits();

        PageImpl page = new PageImpl(collect, pageable, total);

        return page;
    }

    @Override
    public Boolean del(String id) {

        BusinessTraining businessTraining = get(id);
        logService.save("业务培训", businessTraining.getName(),OPERATION_DEL);

        businessTrainingRepository.deleteById(id);

        return true;
    }

    @Override
    public BusinessTraining get(String id) {
        Optional<BusinessTraining> repository = businessTrainingRepository.findById(id);
        if (!repository.isPresent()) {
            throw new BaseException(Status.DATA_NOT_EXIST.getCode(), "未找到业务培训信息！");
        }
        BusinessTraining businessTraining = repository.get();

        return businessTraining;
    }


}
